package com.cnzhy.binding;

import com.cnzhy.config.Function;
import com.cnzhy.config.MapperStatement;
import com.cnzhy.session.MySqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class MyMapperProxy implements InvocationHandler {

    private MySqlSession mySqlSession;

//	private MyConfiguration myConfiguration;

//	public MyMapperProxy(MyConfiguration myConfiguration, MySqlSession mySqlSession) {
//		this.myConfiguration = myConfiguration;
//		this.mySqlSession = mySqlSession;
//	}

    public MyMapperProxy(MySqlSession mySqlSession) {
        this.mySqlSession = mySqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperStatement readMapper = MyMapperRegistry.getMapperBean(method.getDeclaringClass().getName());
        if (readMapper == null) {
            return null;
        }
        // 是否是xml文件对应的接口
        if (!method.getDeclaringClass().getName().equals(readMapper.getInterfaceName())) {
            return null;
        }
        List<Function> functionFist = readMapper.getFunctionList();
        if (functionFist != null && functionFist.size() != 0) {
            for (Function function : functionFist) {
                // id是否和接口方法名一样
                if (method.getName().equals(function.getFuncName())) {
                    if ("select".equals(function.getSqlType()) && method.getName().equals(function.getFuncName())) {
                        return mySqlSession.selectOne(function.getSql(), String.valueOf(args[0]));
                    }
                }
            }
        }
        return null;
    }
}
